/**
 * @Title: HomeActivity.java
 * @Package com.sinoglobal.waitingMe.activity
 * @Description: TODO(用一句话描述该文件做什么)
 * @author hpq
 * @date 2015-8-30 上午11:55:09
 */

package com.sinoglobal.wallet.activity;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.Animation.AnimationListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.sinoglobal.wallet.R;
import com.sinoglobal.wallet.activity.W_SinoBaseActivity;
import com.sinoglobal.wallet.activity.W_SinoBaseActivity.DialogOnClickListener;
import com.sinoglobal.wallet.api.RemoteImpl;
import com.sinoglobal.wallet.app.SinoConstans;
import com.sinoglobal.wallet.entity.W_DynamicKeyEntity;
import com.sinoglobal.wallet.entity.W_HomeBalanceEntity;
import com.sinoglobal.wallet.entity.W_RsVo;
import com.sinoglobal.wallet.entity.W_VerifyPassNumVo;
import com.sinoglobal.wallet.entity.W_WithdrawalSuccessEntity;
import com.sinoglobal.wallet.entity.W_HomeBalanceEntity.RsEntity;
import com.sinoglobal.wallet.task.MyAsyncTask;
import com.sinoglobal.wallet.util.LogUtils;

/**
 * @author clf
 * @createdate 2015-10-22
 * @Description: TODO(余额明细)
 */
public class W_GoodsDetailsActivity extends W_SinoBaseActivity  {

	private TextView good_commit_order;
	public View view1;
	private RelativeLayout pay_fu_bao_layout, pay_weChat_layout,cash_card_layout,pay_wallet_moeny_layout,goods_gopay_layout;
	private ImageView pay_fu_bao_img,pay_weChat_img,cash_card_img,pay_wallet_money_img;
	private int payStyle=0;//支付方式标识
	private PopupWindow mpopupWindow;
	private LinearLayout ll_popup;

	private int cardType;
	private TextView goods_banlance_notice_txt,goods_balance_money_txt;
	public Boolean isShow=false;
	private RelativeLayout good_commit_parent;
	private Button submit_good_price;
	private EditText good_price_txt;
	private String blanceTxt="0.0";
	private String isHaspass;
	private Button set_good_price;
	private int errCount=0;
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.wallet_goods_details_layout);
		mTemplateTitleText.setText("商品详情");
		initView();
		initpopView();
		getData();
		getUnPassWordNum();
	
	}

	private void initView() {
		good_commit_order = (TextView) findViewById(R.id.good_commit_order);
		good_commit_parent = (RelativeLayout) findViewById(R.id.good_commit_parent);
		good_price_txt = (EditText) findViewById(R.id.good_price_txt);
		set_good_price = (Button) findViewById(R.id.set_good_price);
		set_good_price.setOnClickListener(this);
		good_commit_order.setOnClickListener(this);
	}
	public void initpopView() {
		// popwindow相关控件的初始化
		view1 = View.inflate(this, R.layout.wallet_goods_pay_popu_list_layout, null);
		ll_popup = (LinearLayout) view1.findViewById(R.id.goods_pay_popu_layout);
		pay_wallet_moeny_layout = (RelativeLayout) view1.findViewById(R.id.goods_pay_wallet_moeny_layout);
		pay_fu_bao_layout = (RelativeLayout) view1.findViewById(R.id.goods_pay_fu_bao_layout);
		pay_weChat_layout = (RelativeLayout) view1.findViewById(R.id.goods_pay_weChat_layout);
		cash_card_layout = (RelativeLayout) view1.findViewById(R.id.goods_cash_card_layout);
		goods_gopay_layout = (RelativeLayout) view1.findViewById(R.id.goods_gopay_layout);
		pay_fu_bao_img = (ImageView) view1.findViewById(R.id.goods_pay_fu_bao_img);
		pay_weChat_img = (ImageView) view1.findViewById(R.id.goods_pay_weChat_img);
		cash_card_img = (ImageView) view1.findViewById(R.id.goods_cash_card_img);
		pay_wallet_money_img = (ImageView) view1.findViewById(R.id.goods_pay_money_img);
		goods_banlance_notice_txt = (TextView) view1.findViewById(R.id.goods_banlance_notice_txt);
		goods_balance_money_txt = (TextView) view1.findViewById(R.id.goods_balance_money_txt);
		pay_fu_bao_layout.setOnClickListener(this);
		pay_weChat_layout.setOnClickListener(this);
		cash_card_layout.setOnClickListener(this);
		pay_wallet_moeny_layout.setOnClickListener(this);
		goods_gopay_layout.setOnClickListener(this);
		view1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				mpopupWindow.dismiss();
			}
		});

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		int id = v.getId();
		if(id==R.id.good_commit_order){
			ll_popup.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.w_push_bottom_in));
			if (mpopupWindow == null) {
				mpopupWindow = new PopupWindow(this);
				mpopupWindow.setWidth(LayoutParams.MATCH_PARENT);
				mpopupWindow.setHeight(LayoutParams.MATCH_PARENT);
				mpopupWindow.setBackgroundDrawable(new BitmapDrawable());
				mpopupWindow.setFocusable(true);
				mpopupWindow.setOutsideTouchable(true);
			}
			mpopupWindow.setContentView(view1);
			mpopupWindow.showAtLocation(good_commit_order, Gravity.BOTTOM, 0, 0);
			mpopupWindow.update();
			
		}else if(id==R.id.goods_pay_wallet_moeny_layout){//余额支付
			if(errCount>=5){
				showDialog(W_GoodsDetailsActivity.this, "提示", "您今日密码输入次数超限，密码被锁定，请于2小时候后再尝试", "返回", R.color.w_c7, "", R.color.w_c14, false,
						new DialogOnClickListener() {

							@Override
							public void onSure(View v) {
							}

							@Override
							public void onCancle(View v) {
							}
						});
				return;
			}
			if(good_price_txt.getText().toString().equals("")){
				good_price_txt.setText("100");//商品价格默认是100元
				Toast.makeText(W_GoodsDetailsActivity.this, "你未输入价格，默认设置100", 0).show();
			}
			  if(Double.valueOf(good_price_txt.getText().toString())>Double.valueOf(blanceTxt)){
					Toast.makeText(this, "余额不足,请选择其他支付方式", 0).show();
					return;
	          }
			  payStyle=1;
		    goods_banlance_notice_txt.setVisibility(View.GONE);
			pay_wallet_money_img.setVisibility(View.VISIBLE);
			pay_weChat_img.setVisibility(View.GONE);
			pay_fu_bao_img.setVisibility(View.GONE);
			cash_card_img.setVisibility(View.GONE);

		}else if(id==R.id.goods_pay_fu_bao_layout){//支付宝支付
			pay_fu_bao_img.setVisibility(View.VISIBLE);
			pay_weChat_img.setVisibility(View.GONE);
			cash_card_img.setVisibility(View.GONE);
			pay_wallet_money_img.setVisibility(View.GONE);
			payStyle=2;
		}else  if(id==R.id.goods_cash_card_layout){//u付
			pay_fu_bao_img.setVisibility(View.GONE);
			pay_weChat_img.setVisibility(View.GONE);
			pay_wallet_money_img.setVisibility(View.GONE);
			cash_card_img.setVisibility(View.VISIBLE);
			payStyle=3;
			cardType = 1;
		}else if(id==R.id.goods_pay_weChat_layout){//微信支付
			pay_fu_bao_img.setVisibility(View.GONE);
			pay_weChat_img.setVisibility(View.VISIBLE);
			cash_card_img.setVisibility(View.GONE);
			pay_wallet_money_img.setVisibility(View.GONE);
			payStyle=4;
		}else if(id==R.id.set_good_price){//这个以后商品价格固定后删掉，下面代码放到商品价格请求成功返回码下，提前做价格比对
			if(good_price_txt.getText().toString().equals("")){
				good_price_txt.setText("100");//商品价格默认是100元
				Toast.makeText(W_GoodsDetailsActivity.this, "你未输入价格，默认设置100", 0).show();
			}
			if(errCount>=5){
      			 goods_banlance_notice_txt.setVisibility(View.VISIBLE);
		        	  goods_banlance_notice_txt.setText("锁定");
		        	  goods_balance_money_txt.setText("账户余额(剩余"+blanceTxt +"元)");
						pay_fu_bao_img.setVisibility(View.VISIBLE);
						pay_weChat_img.setVisibility(View.GONE);
						cash_card_img.setVisibility(View.GONE);
						pay_wallet_money_img.setVisibility(View.GONE);//余额不足默认选择支付宝
						return;
      			}else if(Double.valueOf(good_price_txt.getText().toString())>=Double.valueOf(blanceTxt)){
				  goods_banlance_notice_txt.setVisibility(View.VISIBLE);
	        	  goods_banlance_notice_txt.setText("不足");
	        	  goods_balance_money_txt.setTextColor(getResources().getColor((R.color.w_payPass_gray)));
	        	  goods_balance_money_txt.setText("账户余额(剩余"+blanceTxt +"元)");
					pay_fu_bao_img.setVisibility(View.VISIBLE);
					pay_weChat_img.setVisibility(View.GONE);
					cash_card_img.setVisibility(View.GONE);
					pay_wallet_money_img.setVisibility(View.GONE);//余额不足默认选择支付宝
					payStyle=2;
					
	          }else{
	        	  goods_balance_money_txt.setText("账户余额(剩余"+blanceTxt +"元)");
	        	  goods_balance_money_txt.setTextColor(Color.BLACK);
	        	  goods_banlance_notice_txt.setVisibility(View.GONE);
	  			pay_wallet_money_img.setVisibility(View.VISIBLE);
	  			pay_weChat_img.setVisibility(View.GONE);
	  			pay_fu_bao_img.setVisibility(View.GONE);
	  			cash_card_img.setVisibility(View.GONE);//余额充足默认选择余额
	  			payStyle=1;
	          }
	}else  if(id==R.id.goods_gopay_layout){//点击支付按钮
		if(payStyle==1){
			getSelectPass();
			showToast("余额支付支付");
		}else if(payStyle==2){
			showToast("支付宝支付");
		}else if(payStyle==3){
			showToast("借记卡支付");
		}else if(payStyle==4){
			showToast("微信支付");

	}
		popuDismiss();
	}else  if(id==R.id.wallet_noData){
			loadError(false);
		}}
	private void popuDismiss() {
		// 向下移动的动画效果
		Animation Animation = AnimationUtils.loadAnimation(this,R.anim.w_push_bottom_out);
		ll_popup.startAnimation(Animation);
		Animation.setAnimationListener(new AnimationListener() {
			@Override
			public void onAnimationStart(Animation animation) {
			}
			@Override
			public void onAnimationRepeat(Animation animation) {
			}
			@Override
			public void onAnimationEnd(Animation animation) {
				LogUtils.v("dismiss--------------");
				mpopupWindow.dismiss();
			}
		});
	}
	//是否设置了支付密码
	private void getSelectPass(){

		MyAsyncTask<W_RsVo> task = new MyAsyncTask<W_RsVo>(true,this,true) {
			@Override
			public W_RsVo before(Void... params) throws Exception {
				// TODO 测试接口
				return RemoteImpl.getInstance().getSelectPassWord(W_GoodsDetailsActivity.this);
			}

			@Override
			public void after(W_RsVo result) {
				if (result != null) {
					if (result.getCode().equals("100") && result.getRs().equals("N")) {
							showDialog(W_GoodsDetailsActivity.this, "提示", "您还没有设置支付密码，为了保障您的财产安全，请设置支付密码",
									"去设置",R.color.w_c14, "等一下",R.color.w_c14,true,new DialogOnClickListener() {
								@Override
								public void onSure(View v) {
									Bundle setting_bundle = new Bundle();
									setting_bundle.putString("title_flag", "3");
									goIntent(W_PayPasswordActivity.class, setting_bundle);//设置密码
								}
								@Override
								public void onCancle(View v) {
//									showToast("取消");
								}
							});
						}else if(result.getCode().equals("100") && result.getRs().equals("Y")){
							Intent intent = new Intent(W_GoodsDetailsActivity.this,W_OrderPayActivity.class);
							Bundle bundle = new Bundle();
							bundle.putString("Money", good_price_txt.getText().toString());
							bundle.putString("Type", "GOOD");//提现页面传来的标示
							intent.putExtras(bundle);
							startActivityForResult(intent,300);
						}
					}else{
						showToast(result.getMsg());
					}
			}

			@Override
			public void exception() {
			}
		};
		task.execute();

	}
	// 获取密码错误次数
			private void getUnPassWordNum() {
				MyAsyncTask<W_VerifyPassNumVo> task = new MyAsyncTask<W_VerifyPassNumVo>(true, this, true) {

					@Override
					public W_VerifyPassNumVo before(Void... params) throws Exception {
						// TODO 测试接口
						return RemoteImpl.getInstance().getUnPassWordNum(W_GoodsDetailsActivity.this);
					}

					@Override
					public void after(W_VerifyPassNumVo result) {

						if (result.getCode().equals("100")) {
							errCount = result.getErrCount();
							if(errCount<5){
							}else{
								 goods_banlance_notice_txt.setVisibility(View.VISIBLE);
					        	  goods_banlance_notice_txt.setText("锁定");
					        	  goods_balance_money_txt.setText("账户余额(剩余"+blanceTxt +"元)");
									pay_fu_bao_img.setVisibility(View.VISIBLE);
									pay_weChat_img.setVisibility(View.GONE);
									cash_card_img.setVisibility(View.GONE);
									pay_wallet_money_img.setVisibility(View.GONE);//余额不足默认选择支付宝
							}
						} else {
							showToast(result.getDescription());
						}

					}

					@Override
					public void exception() {
					}
				};
				task.execute();
			}
	private void getData() {
		MyAsyncTask<W_HomeBalanceEntity> task = new MyAsyncTask<W_HomeBalanceEntity>(true,this,true) {
			

			@Override
			public W_HomeBalanceEntity before(Void... params) throws Exception {
				// TODO 测试接口
				return RemoteImpl.getInstance().getBalance(W_GoodsDetailsActivity.this);
			}

			@Override
			public void after(W_HomeBalanceEntity result) {
				if (result != null) {
					if (result.getCode().equals("100")) {
						RsEntity rs=result.getRs();
						 blanceTxt = rs.getBalance();
						  goods_balance_money_txt.setText("账户余额(剩余"+blanceTxt +"元)");
						  isHaspass = rs.getIsHasPass();
					}else{
						Toast.makeText(W_GoodsDetailsActivity.this, "数据加载失败", 0).show();
					}
				}

			}

			@Override
			public void exception() {
			}
		};
		task.execute();
	}
	@Override
	 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
	        if (requestCode==300&&resultCode==101) {
	                if(data!=null){
	                  String passWord = data.getStringExtra("passWord");
	                  Toast.makeText(W_GoodsDetailsActivity.this, "余额支付开始支付", 0).show();
	                  getDynamicKey(passWord);
	              
	        }
	               
	    }
	        if (requestCode==300&&resultCode==103) {//接收支付密码被锁定后，更改余额支付被锁定状态
            	if(data!=null){
            		errCount = data.getIntExtra("Num", 0);
            		if(errCount>=5){
            			 goods_banlance_notice_txt.setVisibility(View.VISIBLE);
			        	  goods_banlance_notice_txt.setText("锁定");
			        	  goods_balance_money_txt.setText("账户余额(剩余"+blanceTxt +"元)");
							pay_fu_bao_img.setVisibility(View.VISIBLE);
							pay_weChat_img.setVisibility(View.GONE);
							cash_card_img.setVisibility(View.GONE);
							pay_wallet_money_img.setVisibility(View.GONE);//余额不足默认选择支付宝
            			}
            		}
            	}
	      
}	
	// 获取动态秘钥
			private void getDynamicKey( final String password) {
				MyAsyncTask<W_DynamicKeyEntity> task = new MyAsyncTask<W_DynamicKeyEntity>(true, this, true) {
					@Override
					public W_DynamicKeyEntity before(Void... params) throws Exception {
						// TODO 测试接口
						return RemoteImpl.getInstance().getDynamicKey();
					}
					@Override
					public void after(W_DynamicKeyEntity result) {
						 String id="";//
						 String encryptKey="";//动态秘钥
	                    id = result.getId();
	                    encryptKey = result.getEncryptKey();
	                	getWithDrawal(password,id,encryptKey);
					}
					@Override
					public void exception() {
					}
				};
				task.execute();
			}
	// 提现请求（模仿支付功能。支付接口出来后取消）
	private void getWithDrawal(final String password ,final String id, final String encryptKey) {
		MyAsyncTask<W_WithdrawalSuccessEntity> task = new MyAsyncTask<W_WithdrawalSuccessEntity>(true, this, true) {

			@Override
			public W_WithdrawalSuccessEntity before(Void... params) throws Exception {
				// TODO 测试接口
				return RemoteImpl.getInstance().getTiXian(W_GoodsDetailsActivity.this, password, good_price_txt.getText().toString(), getSystemTime(), "1", "1", "89", "0",id,encryptKey);
			}

			@Override
			public void after(W_WithdrawalSuccessEntity result) {

				if (result.getCode().equals("100")) {
					showMidToast("支付成功(用提现接口模仿支付功能)");
					sendBroadcast(result.getRs().getBalance());
				} else {
					Toast.makeText(W_GoodsDetailsActivity.this, result.getRs().getResult(), Toast.LENGTH_SHORT).show();
				}
			}

			@Override
			public void exception() {
			}
		};
		task.execute();
	}
	public String getSystemTime() {
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");// 设置日期格式
		return df.format(new Date());// new Date()为获取当前系统时间}
	}
	private void sendBroadcast(String str) {
		Intent intent = new Intent();
		intent.setAction(SinoConstans.KEY_BalanceReceiver);
		intent.putExtra("Balance", str);
		sendBroadcast(intent);
	}

}
